<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Model\Bill;
use App\Model\CashLog;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class ProfitController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**提现记录
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function outCash(RequestInterface $request):ResponseInterface{
        $page = $request->inputs(['page','limit','cash_type',
            'distributor_id','time', 'status','is_return']);
        $data['list'] = Db::table('cash_log as c')
            ->leftJoin('distributors as d', 'c.distributor_id','=','d.id')
            ->where(function ($query) use ($page) {
                if($page['distributor_id']){
                    $query->where('c.distributor_id',$page['distributor_id']);
                }
                if($page['cash_type']){
                    $query->where('c.cash_type',$page['cash_type']);
                }
                if($page['status']){
                    $query->where('c.status',$page['status']);
                }
                if($page['is_return'] != ''){
                    $query->where('c.is_return',$page['is_return']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('c.created_at', '>=', $page['time'][0]);
                    $query->where('c.created_at', '<=', $page['time'][1]);
                }
            })->orderBy( 'id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->select('c.*','d.name')
            ->get();
        $data['total'] = Db::table('cash_log as c')
            ->leftJoin('distributors as d', 'c.distributor_id','=','d.id')
            ->where(function ($query) use ($page) {
                if($page['distributor_id']){
                    $query->where('c.distributor_id',$page['distributor_id']);
                }
                if($page['status']){
                    $query->where('c.status',$page['status']);
                }
                if($page['cash_type']){
                    $query->where('c.cash_type',$page['cash_type']);
                }
                if($page['is_return'] != ''){
                    $query->where('c.is_return',$page['is_return']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('c.created_at', '>=', $page['time'][0]);
                    $query->where('c.created_at', '<=', $page['time'][1]);
                }
            })->count();
        return $this->success($data);
    }

    /**分润流水记录
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit','out_ord_id',
            'distributor_id','time','payment_type',
            'status']);
        $data['list'] = Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->leftJoin('distributors as d', 'b.account_id','=','d.id')
            ->where(function ($query) use ($page) {
//                if (array_key_exists('keyword',$page) && $page['keyword']) {
//                    $query->where('o.number', '%'.$page['keyword'] . '%');
//                $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
//                }
                $query->where('account_type','App\Model\Distributors');
                if($page['distributor_id']){
                    $query->where('b.account_id',$page['distributor_id']);
                }
                if($page['payment_type']){
                    $query->where('o.payment_type',$page['payment_type']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->orderBy('b.id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->select('b.*', 'o.number as order_number','o.sn','o.channel_number','d.name')
            ->get();
        $data['total'] = Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->leftJoin('distributors as d', 'b.account_id','=','d.id')
            ->where(function ($query) use ($page) {
//                if (array_key_exists('keyword',$page) && $page['keyword']) {
//                    $query->where('o.number', '%'.$page['keyword'] . '%');
//                $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
//                }
                $query->where('account_type','App\Model\Distributors');
                if($page['distributor_id']){
                    $query->where('b.account_id',$page['distributor_id']);
                }
                if($page['payment_type']){
                    $query->where('o.payment_type',$page['payment_type']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->count();
        return $this->success($data);
    }

    public function exportJtList(RequestInterface $request){
        $page = $request->inputs(['out_ord_id', 'time','payment_type', 'status']);
        $query = Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->leftJoin('distributors as d', 'b.account_id','=','d.id')
            ->where(function ($query) use ($page) {
                $query->where('account_type','App\Model\Distributors');
                if($page['payment_type']){
                    $query->where('o.payment_type',$page['payment_type']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
                $query->where('b.account_id',15210);
            })->orderBy('b.id', 'desc');
        $data['list'] = $query->select('b.*', 'o.number as order_number','o.sn','o.channel_number','d.name')
            ->get();
        $data['list'] = json_encode($data['list']);
        $data['list'] = json_decode($data['list'],true);
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        // 设置 Excel 文档的头部
        $sheet->setCellValue('A1', '经销商名称');
        $sheet->setCellValue('B1', '分润金额');
        $sheet->setCellValue('C1', '分润后余额');
        $sheet->setCellValue('D1', '订单号');
        $sheet->setCellValue('E1', '分润时间');
        $sheet->setCellValue('F1', '支付类型');
        foreach (range('A', 'F') as $columnID) {
            $sheet->getColumnDimension($columnID)->setAutoSize(true);
        }

// 设置单元格水平居中的样式数组配置
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];

// 应用样式到第一行的A到O列
        $sheet->getStyle('A:F')->applyFromArray($styleArray);
        // 从第二行开始填充订单数据
        $row = 2;
        foreach ($data['list'] as $order) {
            switch ($order['payment_type']) {
                case 'wx_lite':
                    $order['payment_type'] = '微信';
                    break;
                case 'balance':
                    $order['payment_type'] = '余额';
                    break;
                default:
                    $order['payment_type'] = '支付宝';
                    break;
            }
            $sheet->setCellValue('A' . $row, $order['name'] . ' ');
            $sheet->setCellValue('B' . $row, $order['fee']);
            $sheet->setCellValue('C' . $row, $order['balance']);
            $sheet->setCellValue('D' . $row, $order['order_number']);
            $sheet->setCellValue('E' . $row, $order['created_at']);
            $sheet->setCellValue('F' . $row, $order['payment_type']);
            $row++;
        }
        // 将 Spreadsheet 对象写入 XLSX 文件
        $writer = new Xlsx($spreadsheet);
        // 创建临时文件
        $publicPath = BASE_PATH . '/public/upload/xls/';
        $fileName = date('YmdHis', time()) . '-bills.xlsx';
//        $temp_file = tempnam(sys_get_temp_dir(), $fileName);
        $temp_file = $publicPath . $fileName;
        // 保存到临时文件
        $writer->save($temp_file);
        return $this->success(['url' => 'http://clouds.yimitongxun.com/upload/xls/' . $fileName]);
    }

    public function getJtList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit','out_ord_id', 'time','payment_type', 'status']);
        $query = Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->leftJoin('distributors as d', 'b.account_id','=','d.id')
            ->where(function ($query) use ($page) {
                $query->where('account_type','App\Model\Distributors');
                if($page['payment_type']){
                    $query->where('o.payment_type',$page['payment_type']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
                $query->where('b.account_id',15210);
            })->orderBy('b.id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit']);
        $data['all'] = $query->sum('b.fee');
            $data['total'] = $query->count();
            $data['list'] = $query->select('b.*', 'o.number as order_number','o.sn','o.channel_number','d.name')
            ->get();
        return $this->success($data);
    }
}
